﻿using cn.jpush.api;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Web.Http;
using Ttifa.Infrastructure.Utils;
using Ttifa.WebApiBase;

namespace Ttifa.Push.Controllers
{
    public class JPushController : ApiController
    {
        public ApiResult Push(JPushParam jpushParam)
        {
            var app_key = GetAppKey(jpushParam.App);
            var master_secret = GetMasterSecret(jpushParam.App);

            JPushClient client = new JPushClient(app_key, master_secret);
            var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(jpushParam.extras);
            var pushInfo = new PushPayloadEx(jpushParam.platform);
            pushInfo.SetNotification(jpushParam.platform, jpushParam.title, jpushParam.message, dict);
            if (jpushParam.audience == AudienceEnum.all)
                pushInfo.SetAudience(AudienceEnum.all);
            else
                pushInfo.SetAudience(jpushParam.audience, jpushParam.alias);
            pushInfo.SetOptions(0, IsProduction(jpushParam.App));
            var pushResult = client.SendPush(pushInfo.Value);
            if (!pushResult.isResultOK())
            {
                return new ApiResult(ApiStatus.Fail, pushResult.ToString());
            }

            return new ApiResult();
        }

        private string GetAppKey(TerminalApp app)
        {
            return ConfigManager.GetSetting($"JPush.{app.ToString()}.App_Key");
        }

        private string GetMasterSecret(TerminalApp app)
        {
            return ConfigManager.GetSetting($"JPush.{app.ToString()}.Master_Secret");
        }

        private bool IsProduction(TerminalApp app)
        {
            return ConfigManager.GetSetting($"JPush.{app.ToString()}.Env").ToLower() == "production";
        }
    }
}
